package com.earthea.scaffold.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.earthea.cache.CacheService;
import com.earthea.scaffold.common.constant.Constants;
import com.earthea.scaffold.common.entity.BaseRsp;
import com.earthea.scaffold.common.enums.CacheEnum;
import com.earthea.scaffold.system.entity.response.CaptchaRsp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 验证码操作处理
 */
@RestController
@RequestMapping("/api")
public class CaptchaController {

    @Value("${app.captcha.enabled:true}")
    private boolean captchaEnabled;

    @Autowired
    private CacheService cacheService;

    private final ICaptcha captcha;

    public CaptchaController() {
        this.captcha = CaptchaUtil.createLineCaptcha(200, 100);
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public BaseRsp getCode() {
        CaptchaRsp response = BaseRsp.success(CaptchaRsp.class);
        response.setCaptchaEnabled(captchaEnabled);
        if (!captchaEnabled) {
            return response;
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheEnum.CAPTCHA_CODE.getCacheKey(uuid);

        captcha.createCode();
        String code = captcha.getCode();

        cacheService.setex(verifyKey, code, 120);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        captcha.write(os);
        response.setUuid(uuid);
        response.setImg(Base64.encode(os.toByteArray()));
        return response;
    }
}
